<template>
	<div>
		<canvas width="200" height="200" id="canvas"	ref="canvas"></canvas>
	</div>
</template>
<script type="text/javascript">
	import { Game, GameObject, Component } from '@eva/eva.js'
	import { RendererSystem } from '@eva/plugin-renderer'
	import { Graphics, GraphicsSystem } from '@eva/plugin-renderer-graphics'
	class Move extends Component {
		static componentName = 'Move';
		speed = {
			// 移动速度
			x: 100,
			y: 200,
		};
		init(obj) {
			Object.assign(this, obj);
		}
		update(e) {
			// 每秒 N 像素
			// console.log(e)
			const position = this.gameObject.transform.position;
			this.gameObject.transform.position.x += this.speed.x * (e.deltaTime / 1000);
			this.gameObject.transform.position.y += this.speed.y * (e.deltaTime / 1000);
			if (position.x >= 350 || position.x <= 0) {
				this.speed.x = -this.speed.x;
			}
			if (position.y >= 350 || position.y <= 0) {
				this.speed.y = -this.speed.y;
			}
		}
		onPause() {
			this.oldSpeed = this.speed;
			this.speed = {
				x: 0,
				y: 0,
			};
		}
		onPlay() {
			this.speed = this.oldSpeed;
		}
	}
	export default{
		name: 'EvajsStudyShowComponent',
		data(){
			return {
				percent: 0,
				game: null
			}
		},
		created(){
			this.$nextTick(()=>{
				this.ShowComponent()
			})
		},
		destroyed(){
			if(this.game){
				this.game.destroy()
			}
		},
		methods:{
			ShowComponent(){
				// 创建游戏
				const game = new Game({
					systems: [ // 游戏添加渲染系统
						new RendererSystem({
							canvas: this.$refs.canvas,
							width: 400,
							height: 400,
						}),
						// 游戏图形系统
						new GraphicsSystem(),
					],
				});
				this.showRect(game)
			},
			showRect(game){
				// 游戏对象
				this.rect = new GameObject('rect', {
					position: {
						x: 50,
						y: 50
					},
					size: {
						width: 300,
						height: 20
					}
				})
				// 游戏对象内添加文本内容
				const outterComponent = rect.addComponent(new Graphics())
				outterComponent.graphics.beginFill(0xde0000, 1)
				outterComponent.graphics.drawRect(0, 0, 50, 50)
				outterComponent.graphics.endFill()

				rect.addComponent(new Move({
					speed: {
						x: 250,
						y: 200,
					},
				}))

				this.game.scene.addChild(rect);
			}
		}
	}
</script>